<?php

namespace builder\widget\ajax;

use builder\helper\H5;
use builder\helper\Url;
use builder\widget\BaseWidget;
use yii\base\InvalidArgumentException;
use yii\helpers\Json;

/**
 * 块组件(ajax)
 * ```php
 *  WidgetFacade::echo2Return(function () {
 *              BlockAjax::begin([
 *                 'url' => 'user/create',
 *                 'ajaxFailureCallback' => 'console.log(scope.$parent.default1.Field1=2)',
 *                 'scope' => [
 *                      'param1' => 'default1.Field1',
 *                 ],
 *              ]);
 *              echo '<button class="layui-btn layui-btn-sm layui-bg-light layui-border-theme"><i class="bi bi-box-arrow-in-down-right"></i> 动态按钮(ajax)</button>';
 *              BlockAjax::end();
 * });
 *
 * ```
 */
class BlockAjax extends BaseWidget
{
    /**
     * @var array|string ajax路由/地址
     */
    public $url;

    /**
     * @var string Http动作，仅 GET、POST。
     */
    public $method = 'POST';

    /**
     * @var string 询问标题
     */
    public $questionTitle = '';

    /**
     * @var string 询问描述
     */
    public $questionDescription = '';

    /**
     * @var null|string ajax返回成功后回调，填写javascript表达式。
     */
    public $ajaxSuccessCallback = null;

    /**
     * @var null|string ajax返回失败后回调，填写javascript表达式。
     */
    public $ajaxFailureCallback = null;

    /**
     * angular字段
     * @var null|array
     */
    public $scope = null;

    /**
     * @var array 其他选项，如：attribute、class、style。
     */
    public $options = [];

    /**
     * @return void
     */
    public function initOptions()
    {
        if (empty($this->url)) {
            throw new InvalidArgumentException('The class ' . __CLASS__ . '::url is empty.');
        }

        $this->url = Url::to($this->url, '');
    }

    /**
     * {@inheritdoc}
     */
    public function init()
    {
        parent::init();

        $this->initOptions();

        echo H5::beginTag('ngx-block', array_merge($this->options, [
                'type' => 'ajax',
                'url' => $this->url,
                'method' => $this->method,
                'question-title' => $this->questionTitle,
                'question-description' => $this->questionDescription,
                'ajax-success-callback' => $this->ajaxSuccessCallback,
                'ajax-failure-callback' => $this->ajaxFailureCallback,
                'scope' => $this->scope ? Json::htmlEncode($this->scope) : '',
            ])) . "\n";
    }

    /**
     * {@inheritdoc}
     */
    public function run()
    {
        echo H5::endTag('ngx-block') . "\n";
    }
}